package com.neutech.servlet;

import a.Filter;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.logging.Logger;

public class LoggingFilter implements Filter {
    private static final Logger logger =Logger.getLogger(LoggingFilter.class.getName());
    public void init(FilterConfig filterConfig) throws SecurityException{

    }
    public void doFiler(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest =(HttpServletRequest) request;
        HttpServletResponse httpResponse =(HttpServletResponse) response;
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        String requestMethod = httpRequest.getMethod();
        String requestURI = httpRequest.getRequestURI();
        HttpSession session =httpRequest.getSession(false);
        String sessionId = session != null ? session.getId():"N/A";
        Long startTime =System.currentTimeMillis();
        logger.info("请求开始:"+requestMethod+" "+requestURI+"SessionId:"+sessionId);
        chain.doFilter(request,response);
        long endTime = System.currentTimeMillis();
        logger.info("请求完成:"+requestMethod+" "+requestURI+"SessionId:"+sessionId+"时间"+(endTime-startTime)+"ms");
    }
    public void destroy(){
        //Clean up resources
    }
}
